package com.example.reggie.utility;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器(支持通配符)
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        //判断路径
        String requestURI = request.getRequestURI();
        String[] ursl = new String[]{
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };

        if (check(ursl,requestURI)){
            filterChain.doFilter(request,response);
            return;
        }

        //pc判断登录
        //ps：黑马这里只是效验了请求头是否存在 我认为不合理 应该使用jwt令牌并结合数据库保持时效性
        if (request.getSession().getAttribute("employee")!=null){
            //设计线程变量(用户id)
            BaseContext.setCurrentId((Long)request.getSession().getAttribute("employee"));
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //pe判断登录
        //ps：黑马这里只是效验了请求头是否存在 我认为不合理 应该使用jwt令牌并结合数据库保持时效性
        if (request.getSession().getAttribute("user")!=null){
            //设计线程变量(用户id)
            BaseContext.setCurrentId((Long)request.getSession().getAttribute("user"));
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //逆天前端根据msg判断？？？？
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
    //路径匹配
    public boolean check(String[] ursl,String requestURI){
        for (String url : ursl) {
            boolean match = PATH_MATCHER.match(url,requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
